<template>
  <div class="tasks-by-date-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <div class="header-left">
            <el-button 
              type="primary" 
              :icon="ArrowLeft" 
              @click="handleBack"
              size="small"
            >
              返回
            </el-button>
            <h2 class="page-title">{{ formatPageTitle(selectedDate) }}</h2>
          </div>
          <div class="header-right">
            <el-tag type="info" size="large">
              共 {{ filteredTasks.length }} 个任务
            </el-tag>
          </div>
        </div>
      </template>

      <!-- 筛选条件 -->
      <div class="filter-section" v-if="tasks.length > 0">
        <el-row :gutter="16" class="mb-4">
          <el-col :span="8">
            <el-select 
              v-model="selectedAssignee" 
              placeholder="按负责人筛选" 
              style="width: 100%"
              clearable
            >
              <el-option label="全部" value="" />
              <el-option 
                v-for="assignee in availableAssignees" 
                :key="assignee.name"
                :label="assignee.name" 
                :value="assignee.name"
              />
            </el-select>
          </el-col>
        </el-row>
      </div>

      <!-- 统计信息 -->
      <div class="stats-section" v-if="taskStats.total > 0">
        <el-row :gutter="16">
          <el-col :xs="12" :sm="6" :md="4" :lg="3" v-for="(stat, key) in taskStats" :key="key">
            <div class="stat-card" v-if="typeof stat === 'number'">
              <div class="stat-label">{{ getStatLabel(key) }}</div>
              <div class="stat-value">{{ stat }}</div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 任务列表 -->
      <div class="tasks-section">
        <el-table
          :data="filteredTasks"
          stripe
          v-loading="loading"
          empty-text="该日期没有任务"
        >
          <el-table-column prop="title" label="任务标题" min-width="200">
            <template #default="{ row }">
              <div class="task-title-cell">
                <span class="task-title" @click="handleViewTask(row.id)">{{ row.title }}</span>
                <div class="task-tags">
                  <el-tag v-if="row.task_type" size="small" type="info">{{ getTypeText(row.task_type) }}</el-tag>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="project_name" label="所属项目" width="150" />
          
          <el-table-column prop="version_name" label="关联版本" width="180">
            <template #default="{ row }">
              <el-link 
                v-if="row.version_id && (row.version_number || row.version_name)" 
                type="primary" 
                @click="handleViewVersion(row.version_id)"
                class="version-link"
              >
                <template v-if="row.version_number && row.version_name">
                  {{ row.version_number }} - {{ row.version_name }}
                </template>
                <template v-else-if="row.version_number">
                  {{ row.version_number }}
                </template>
                <template v-else>
                  {{ row.version_name }}
                </template>
              </el-link>
              <span v-else class="text-gray-400">未关联</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="priority" label="优先级" width="100">
            <template #default="{ row }">
              <el-tag :type="getPriorityType(row.priority)" size="small">
                {{ getPriorityText(row.priority) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="assignee_name" label="负责人" width="140">
            <template #default="{ row }">
              <UserDisplay
                v-if="row.assignee_id"
                :user-id="row.assignee_id"
                :user-name="row.assignee_name"
                :user-avatar="row.assignee_avatar"
                :show-avatar="true"
                size="small"
              />
              <span v-else style="color: #909399;">未分配</span>
            </template>
          </el-table-column>
          
          <el-table-column prop="progress" label="进度" width="120">
            <template #default="{ row }">
              <el-progress :percentage="row.progress || 0" :stroke-width="8" />
            </template>
          </el-table-column>
          
          <el-table-column prop="due_date" label="截止日期" width="120">
            <template #default="{ row }">
              <span :class="getDueDateClass(row.due_date)">
                {{ formatDate(row.due_date) || '未设置' }}
              </span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click="handleViewTask(row.id)">查看</el-button>
              <el-button size="small" @click="handleEditTask(row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 任务详情对话框 -->
    <TaskViewDialog
      v-model="viewDialogVisible"
      :task-id="selectedTaskId"
      @updated="handleTaskUpdated"
    />
    
    <!-- 任务编辑对话框 -->
    <TaskEditDialog
      v-model="editDialogVisible"
      :task-id="selectedTaskId"
      :task="selectedTask || undefined"
      @success="handleTaskUpdated"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { useStateStore } from '@/stores/state'
import { priorityApi } from '@/api/priority'
import { ModuleType } from '@/types/core'
import { getTasks } from '@/api/tasks'
import { ResponseParser } from '@/utils/responseParser'
import type { Task } from '@/types/task'
import TaskViewDialog from '@/components/task/TaskViewDialog.vue'
import TaskEditDialog from '@/components/task/TaskEditDialog.vue'
import UserDisplay from '@/components/ui/UserDisplay.vue'

const route = useRoute()
const router = useRouter()

// 状态管理
const stateStore = useStateStore()

// 响应式数据
const loading = ref(false)
const selectedDate = ref<string>('')
const tasks = ref<Task[]>([])
const selectedTaskId = ref('')
const selectedTask = ref<Task | null>(null)
const viewDialogVisible = ref(false)
const editDialogVisible = ref(false)
const selectedAssignee = ref('')

// 任务状态和优先级选项
const taskStatuses = computed(() => {
  const taskStates = stateStore.getStatesByModule(ModuleType.TASK)
  return taskStates.map(state => ({
    value: state.code,
    label: state.name,
    color: state.color || '#909399'
  }))
})

const taskPriorities = ref<any[]>([])

// 任务统计 - 动态统计所有状态
const taskStats = computed(() => {
  // 动态统计，使用所有任务状态代码
  const stats: Record<string, number> = {
    total: filteredTasks.value.length
  }
  
  // 动态统计各状态的任务数量
  filteredTasks.value.forEach(task => {
    const statusCode = task.status
    if (statusCode) {
      // 从状态管理系统获取状态信息，使用状态代码作为统计key
      if (!stats[statusCode]) {
        stats[statusCode] = 0
      }
      stats[statusCode]++
    }
  })
  
  return stats
})

// 可用负责人列表（从任务数据中提取）
const availableAssignees = computed(() => {
  const assigneesMap = new Map<string, { name: string }>()
  
  tasks.value.forEach(task => {
    if (task.assignee_name) {
      assigneesMap.set(task.assignee_name, { name: task.assignee_name })
    }
  })
  
  // 添加未分配选项
  assigneesMap.set('未分配', { name: '未分配' })
  
  return Array.from(assigneesMap.values())
    .filter(assignee => assignee.name)
    .sort((a, b) => a.name.localeCompare(b.name))
})

// 过滤任务：只显示选中日期的任务，并按负责人筛选
const filteredTasks = computed(() => {
  if (!selectedDate.value) return []
  
  const targetDate = selectedDate.value.split('T')[0]
  
  return tasks.value.filter(task => {
    // 按日期过滤
    let dateMatch = false
    
    // 检查截止日期
    if (task.due_date) {
      const dueDate = task.due_date.split('T')[0]
      if (dueDate === targetDate) dateMatch = true
    }
    
    // 检查开始日期
    if (!dateMatch && task.start_date) {
      const startDate = task.start_date.split('T')[0]
      if (startDate === targetDate) dateMatch = true
    }
    
    if (!dateMatch) return false
    
    // 按负责人过滤
    if (selectedAssignee.value === '') {
      return true // 不筛选负责人
    } else if (selectedAssignee.value === '未分配') {
      return !task.assignee_name || task.assignee_name.trim() === ''
    } else {
      return task.assignee_name === selectedAssignee.value
    }
  })
})

// 格式化页面标题
const formatPageTitle = (date: string) => {
  if (!date) return '任务列表'
  const dateObj = new Date(date)
  const year = dateObj.getFullYear()
  const month = dateObj.getMonth() + 1
  const day = dateObj.getDate()
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  const weekday = weekdays[dateObj.getDay()]
  return `${year}年${month}月${day}日 ${weekday} 的任务`
}

// 获取统计标签（使用动态状态）
const getStatLabel = (key: string) => {
  if (key === 'total') {
    return '总计'
  }
  // 使用动态状态获取标签
  const statusOption = taskStatuses.value.find(s => s.value === key)
  if (statusOption) {
    return statusOption.label
  }
  return key
}

// 获取任务类型文本
const getTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    feature: '功能',
    bug: '缺陷',
    improvement: '改进',
    task: '任务'
  }
  return typeMap[type] || type
}

// 获取状态类型 - 从状态管理系统动态获取
const getStatusType = (status: string): 'success' | 'info' | 'warning' | 'danger' => {
  const statusOption = taskStatuses.value.find(s => s.value === status)
  if (statusOption) {
    // 根据状态名称判断类型
    const name = statusOption.label?.toLowerCase() || ''
    const code = statusOption.value?.toLowerCase() || ''
    if (name.includes('完成') || code.includes('done') || code.includes('completed')) {
      return 'success'
    }
    if (name.includes('进行中') || name.includes('处理中') || code.includes('in_progress')) {
      return 'warning'
    }
    if (name.includes('审核') || name.includes('评审') || code.includes('review')) {
      return 'warning'
    }
    if (name.includes('取消') || code.includes('cancelled')) {
      return 'danger'
    }
  }
  return 'info'
}

// 获取状态文本（使用动态状态）
const getStatusText = (status: string) => {
  const statusOption = taskStatuses.value.find(s => s.value === status)
  if (statusOption) {
    return statusOption.label
  }
  // 如果状态管理系统中没有找到，直接返回状态代码
  return status
}

// 获取优先级类型
const getPriorityType = (priority: string): 'success' | 'info' | 'warning' | 'danger' => {
  const priorityMap: Record<string, 'success' | 'info' | 'warning' | 'danger'> = {
    low: 'info',
    medium: 'success',
    high: 'warning',
    urgent: 'danger',
    critical: 'danger'
  }
  return priorityMap[priority] || 'info'
}

// 获取优先级文本（使用动态优先级）
const getPriorityText = (priority: string) => {
  const priorityOption = taskPriorities.value.find(p => p.value === priority)
  if (priorityOption) {
    return priorityOption.label
  }
  // 兼容默认标签
  const priorityMap: Record<string, string> = {
    low: '低',
    medium: '中',
    high: '高',
    urgent: '紧急',
    critical: '严重'
  }
  return priorityMap[priority] || priority
}

// 格式化日期
const formatDate = (date?: string) => {
  if (!date) return ''
  try {
    const dateObj = new Date(date)
    return dateObj.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' })
  } catch {
    return date
  }
}

// 获取截止日期样式类
const getDueDateClass = (dueDate?: string) => {
  if (!dueDate) return ''
  
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  const due = new Date(dueDate)
  due.setHours(0, 0, 0, 0)
  const diffTime = due.getTime() - today.getTime()
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays < 0) return 'overdue'
  if (diffDays <= 3) return 'due-soon'
  return ''
}

// 获取任务列表
const fetchTasks = async () => {
  loading.value = true
  try {
    const response = await getTasks({
      page: 1,
      size: 1000 // 获取足够多的任务以筛选
    })
    const parsedResponse = ResponseParser.parseTaskListResponse(response)
    tasks.value = parsedResponse.items
  } catch (error) {
    console.error('获取任务列表失败:', error)
    const errorMessage = ResponseParser.extractMessage(error) || '获取任务列表失败'
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
  }
}

// 返回任务管理页面（日历视图）
const handleBack = () => {
  // 导航到包含日历视图的任务管理页面
  router.push({ name: 'Tasks' })
}

// 查看任务
const handleViewTask = (taskId: string) => {
  selectedTaskId.value = taskId
  viewDialogVisible.value = true
}

// 编辑任务
const handleEditTask = (task: Task) => {
  selectedTask.value = task
  selectedTaskId.value = task.id
  editDialogVisible.value = true
}

// 任务更新后刷新
const handleTaskUpdated = () => {
  fetchTasks()
}

// 查看版本详情
const handleViewVersion = (versionId: string) => {
  router.push(`/versions/${versionId}`)
}

// 获取基础数据
const fetchBaseData = async () => {
  try {
    // 获取任务优先级
    const priorityResponse = await priorityApi.getAll('task')
    if (priorityResponse.data.success) {
      taskPriorities.value = priorityResponse.data.data.map((p: any) => ({
        value: p.code,
        label: p.name,
        color: p.color,
        sort_order: p.sort_order || 0
      }))
    }
  } catch (error) {
    console.error('获取任务优先级失败:', error)
  }
}

// 初始化
onMounted(async () => {
  // 初始化状态数据
  await stateStore.fetchStates({ module_type: ModuleType.TASK })
  
  // 获取基础数据
  await fetchBaseData()
  
  const date = route.query.date as string
  if (date) {
    selectedDate.value = date
  } else {
    // 如果没有日期参数，使用今天
    selectedDate.value = new Date().toISOString().split('T')[0]
  }
  
  fetchTasks()
})
</script>

<style lang="scss" scoped>
.tasks-by-date-page {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;
      
      .page-title {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: #1f2937;
      }
    }
    
    .header-right {
      display: flex;
      align-items: center;
      gap: 12px;
    }
  }
  
  .filter-section {
    margin-bottom: 20px;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px solid #e5e7eb;
  }
  
  .stats-section {
    margin-bottom: 24px;
    padding: 20px;
    background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
    border-radius: 8px;
    border: 1px solid #e5e7eb;
    overflow-x: auto;
    
    .stat-card {
      text-align: center;
      padding: 16px;
      background: #ffffff;
      border-radius: 8px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      transition: all 0.2s ease;
      min-width: 120px; /* 确保卡片有最小宽度 */
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
      }
      
      .stat-label {
        font-size: 12px;
        color: #6b7280;
        margin-bottom: 8px;
      }
      
      .stat-value {
        font-size: 24px;
        font-weight: 700;
        color: #1f2937;
      }
    }
  }
  
  .tasks-section {
    .task-title-cell {
      display: flex;
      flex-direction: column;
      gap: 4px;
      
      .task-title {
        font-weight: 500;
        color: #3b82f6;
        cursor: pointer;
        transition: color 0.2s ease;
        
        &:hover {
          color: #2563eb;
          text-decoration: underline;
        }
      }
      
      .task-tags {
        display: flex;
        gap: 4px;
      }
    }
    
    .assignee-cell {
      display: flex;
      align-items: center;
      gap: 8px;
    }
    
    .text-gray-400 {
      color: #9ca3af;
    }
    
    .overdue {
      color: #ef4444;
      font-weight: 600;
    }
    
    .due-soon {
      color: #f59e0b;
      font-weight: 600;
    }
  }
}
</style>

